package com.servicesystem.servicesystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.servicesystem.servicesystem.entity.douyin.GoodsLib;
import com.servicesystem.servicesystem.entity.douyin.Product;
import com.servicesystem.servicesystem.entity.douyin.vo.oauth.OauthVO;
import com.servicesystem.servicesystem.entity.douyin.vo.product.AddProductSkuVO;
import com.servicesystem.servicesystem.entity.douyin.vo.product.AddProductVO;
import com.servicesystem.servicesystem.entity.douyin.vo.product.AddSpecsVO;
import com.servicesystem.servicesystem.mapper.ProductMapper;
import com.servicesystem.servicesystem.service.GoodsLibService;
import com.servicesystem.servicesystem.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.servicesystem.servicesystem.untis.Http;
import com.servicesystem.servicesystem.untis.ali.StringUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author X
 * @since 2020-09-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private static final String app_key = "6845190554020480520";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsLibService goodsLibService;

    /***
     * 向抖店添加商品
     * @param addProductVO
     */
    @Override
    public String addProduct(AddProductVO addProductVO) throws Exception {

        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);
        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("brand_id", addProductVO.getBrandId());
        //linkedHashMap.put("class_quality", addProductVO.getClassQuality());
        linkedHashMap.put("delivery_delay_day", addProductVO.getDeliveryDelayDay());
        linkedHashMap.put("description", addProductVO.getDescriptionStr());
        linkedHashMap.put("discount_price", addProductVO.getDiscountPrice());
        linkedHashMap.put("first_cid", addProductVO.getFirstCid());
        linkedHashMap.put("market_price", addProductVO.getMarketPrice());
        linkedHashMap.put("mobile", addProductVO.getMobile());
        linkedHashMap.put("name", addProductVO.getName());
        linkedHashMap.put("out_product_id", addProductVO.getOfferId());
        linkedHashMap.put("pay_type", addProductVO.getPayType());
        linkedHashMap.put("pic", addProductVO.getPicStr());
        linkedHashMap.put("product_format", addProductVO.getProductFormat());
        //linkedHashMap.put("presell_type", addProductVO.getPresellType());
        //linkedHashMap.put("presell_delay", addProductVO.getPresellDelay());
        //linkedHashMap.put("presell_end_time", addProductVO.getPresellEndTime());
        //linkedHashMap.put("quality_report", addProductVO.getQualityReport());
        //linkedHashMap.put("recommend_remark", addProductVO.getRecommendRemark());
        linkedHashMap.put("second_cid", addProductVO.getSecondCid());
        linkedHashMap.put("spec_id", addProductVO.getSpecId());
        linkedHashMap.put("spec_pic", addProductVO.getSpecPic());
        linkedHashMap.put("third_cid", addProductVO.getThirdCid());
        linkedHashMap.put("weight", addProductVO.getWeight());

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "product.add";
        //拼接url
        String url = "http://openapi-fxg.jinritemai.com/product/add?app_key=" + app_key + "&access_token=" + access_token + "&method=product.add&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);
        System.out.println(url);
        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);

        Map map = JSON.parseObject(result, Map.class);
        Object data = map.get("data");
        if (ObjectUtils.isEmpty(data)) {
            return result;
        }
        JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(data));
        Map map1 = JSON.parseObject(JSON.toJSONString(parseObject), Map.class);
        Object product_id = map1.get("product_id");
        String productIdStr = JSON.toJSONString(product_id);
        String offerId = addProductVO.getOfferId();
        GoodsLib goodsLib = new GoodsLib();
        goodsLib.setProductId(productIdStr);
        QueryWrapper<GoodsLib> goodsLibQueryWrapper = new QueryWrapper<>();
        goodsLibQueryWrapper.eq("offer_id", offerId);
        goodsLibService.update(goodsLib, goodsLibQueryWrapper);
        return result;
    }

    /***
     * 添加商品规格
     * @param addSpecsVO
     * @return
     */
    @Override
    public String addSpec(AddSpecsVO addSpecsVO) throws Exception {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("name", addSpecsVO.getName());
        linkedHashMap.put("specs", addSpecsVO.getSpecs());

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "spec.add";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/spec/add?app_key=" + app_key + "&access_token=" + access_token + "&method=spec.add&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获得规格
     * @return
     */
    @Override
    public String getSpec() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(null, null);

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String method = "spec.list";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/spec/list?app_key=" + app_key + "&access_token=" + access_token + "&method=spec.list&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取商品分类列表
     * @param cunt
     * @return
     */
    @Override
    public String getGoodsCategory(String cunt) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("cid", cunt);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "product.getGoodsCategory";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/product/getGoodsCategory?app_key=" + app_key + "&access_token=" + access_token + "&method=product.getGoodsCategory&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 添加商品SKU
     * @param addProductSkuVO
     * @return
     */
    @Override
    public String addGoodsSku(AddProductSkuVO addProductSkuVO) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("out_sku_id", addProductSkuVO.getOutSkuId());
        linkedHashMap.put("price", addProductSkuVO.getPrice());
//        linkedHashMap.put("product_id", addProductSkuVO.getProductId());
        linkedHashMap.put("settlement_price", addProductSkuVO.getSettlementPrice());
        linkedHashMap.put("spec_detail_ids", addProductSkuVO.getSpecDetailIds());
        linkedHashMap.put("spec_id", addProductSkuVO.getSpecId());
        linkedHashMap.put("stock_num", addProductSkuVO.getStockNum());

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "sku.add";

        //拼接url
        String url = "http://openapi-fxg.jinritemai.com/sku/add?app_key=" + app_key + "&access_token=" + access_token + "&method=sku.add&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取规格列表
     * @return
     */
    @Override
    public String getSpecList() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(null, null);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "spec.list";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/spec/list?app_key=" + app_key + "&access_token=" + access_token + "&method=spec.list&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取规格详情
     * @param specId
     * @return
     */
    @Override
    public String getSpecDetail(String specId) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("id", specId);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "spec.specDetail";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/spec/specDetail?app_key=" + app_key + "&access_token=" + access_token + "&method=spec.specDetail&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 批量添加添加商品SKU
     * @param addProductSkuVO
     * @return
     */
    @Override
    public String addGoodsSkuAll(AddProductSkuVO addProductSkuVO) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("out_product_id", addProductSkuVO.getOfferId());
        linkedHashMap.put("out_sku_id", addProductSkuVO.getOutSkuId());
        linkedHashMap.put("price", addProductSkuVO.getPrice());
//        linkedHashMap.put("product_id", addProductSkuVO.getProductId());
        linkedHashMap.put("settlement_price", addProductSkuVO.getSettlementPrice());
        linkedHashMap.put("spec_detail_ids", addProductSkuVO.getSpecDetailIds());
        linkedHashMap.put("spec_id", addProductSkuVO.getSpecId());
        linkedHashMap.put("stock_num", addProductSkuVO.getStockNum());

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "sku.addAll";

        //拼接url
        String url = "http://openapi-fxg.jinritemai.com/sku/addAll?app_key=" + app_key + "&access_token=" + access_token + "&method=sku.addAll&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取商品sku列表
     * @param productId
     * @return
     */
    @Override
    public String getSkuList(String productId) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("product_id", productId);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "sku.list";

        //拼接url
        String url = "http://openapi-fxg.jinritemai.com/sku/list?app_key=" + app_key + "&access_token=" + access_token + "&method=sku.list&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 删除抖店商品
     * @param productId
     * @return
     */
    @Override
    public String deleteProduct(String productId) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("product_id", productId);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "product.del";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/product/del?app_key=" + app_key + "&access_token=" + access_token + "&method=product.del&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取商品详细
     * @param productId
     * @return
     */
    @Override
    public String productDetail(String productId) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("product_id", productId);

        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "product.detail";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/product/detail?app_key=" + app_key + "&access_token=" + access_token + "&method=product.detail&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }


    public String sign(String app_key, String mapStr, String method, String format2) {
        String secret = "8963b551-bd04-4be5-b02b-2e82ee0fccdb";
        String str = secret + "app_key" + app_key + "method" + method + "param_json" + mapStr + "timestamp" + format2 + "v2" + secret;
        String res = stringToMD5(str);
        return res;
    }


    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        while (md5code.length() < 32) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }
}
